//
//  HSYAlertView.m
//  高仿暴走斗图
//
//  Created by huangsongyao on 16/4/4.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYAlertView.h"
#import "HSYAlertView+Animation.h"
#import "NSString+Replace.h"
#import "UILabel+SuggestSize.h"
#import "UIButton+RAC.h"

#define BGROUND                         10.0
#define ALERTVIEW_BUTTON_HEIGHT         45.0f
#define CLEARANCE                       5.0f
@interface HSYAlertView ()

@property (nonatomic, strong) UIWindow *window;                 //整个阴影覆盖
@property (nonatomic, strong) UIView *alpView;                  //整个阴影笼罩下的alpha View，用于是否有阴影笼罩效果

@end

@implementation HSYAlertView

- (instancetype)init {
    
    if (self = [super init]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.window = [UIScreen getKeyWindows];
    self.frame = self.window.frame;
    
    self.backgroundColor = CLEAR_COLOR;
    self.clipsToBounds = YES;
    
    self.alpView = [[UIView alloc] initWithFrame:self.frame];
    self.alpView.backgroundColor = CLEAR_COLOR;
    self.alpView.alpha = self.alpha;
    [self addSubview:self.alpView];
    
    _backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    self.backgroundView.backgroundColor = CLEAR_COLOR;
    self.backgroundView.clipsToBounds = YES;
    [self.backgroundView.layer setCornerRadius:BGROUND];
    [self addSubview:self.backgroundView];
    
    _backgroundImage = [[UIImageView alloc] initWithFrame:self.backgroundView.bounds];
    UIImage *img = [[HSYColorHelper shareInstance] canvasImageWithColor:[UIColor whiteColor]];
    self.backgroundImage.image = img;
    self.backgroundImage.highlightedImage = img;
    self.backgroundImage.backgroundColor = CLEAR_COLOR;
    [self.backgroundView addSubview:self.backgroundImage];
    
    self.titleFont = HSYFONTSIZE(16);
    self.titleColor = [UIColor blackColor];
    
    self.contentFont = HSYFONTSIZE(15);
    self.contentColor = [UIColor blackColor];
    
    self.animationType = kCustomAlertViewAnimationTypeZoomIn;
}


#pragma mark - Clear All View

- (void)destroyView {
    
    for (UIView *item in self.backgroundView.subviews) {
        
        if (item != self.backgroundImage) {
            [item removeFromSuperview];
        }
    }
}


#pragma mark - Show AlertView

- (void)showAlert {
    
    [self removeFromSuperview];
    [self.window addSubview:self];
    self.isDisplay = YES;
    [self alertViewAnimation];
}


- (void)alertViewAnimation {
    
    if (_isDisplay) {
        switch (self.animationType) {
            case kCustomAlertViewAnimationTypeFadeIn:
                [self fadeIn];
                break;
            case kCustomAlertViewAnimationTypeZoomIn:
                [self zoomIn];
                break;
            case kCustomAlertViewAnimationTypeMoveIn:
                [self moveIn];
                break;
            default:
                break;
        }
    } else {
        switch (_animationType) {
            case kCustomAlertViewAnimationTypeFadeOut:
                [self fadeOut];
                break;
            case kCustomAlertViewAnimationTypeZoomOut:
                [self zoomOut];
                break;
            case kCustomAlertViewAnimationTypeMoveOut:
                [self moveOut];
                break;
            default:
                break;
        }
    }
}


- (void)didDismissEndingForAnimationType:(kCustomAlertViewAnimationType)animationType {
    
    self.animationType = animationType;
    self.isDisplay = NO;
    [self alertViewAnimation];
}


#pragma mark - UI

- (UIButton *)createButtonForImage:(UIImage *)image withHighImage:(UIImage *)hImage title:(NSString *)title highTitle:(NSString *)hTitle signalCompletion:(void(^)(id x))completion {
    
    UIButton *button = [UIButton rac_createButtonForBackgroundImage:image
                                                      withHighImage:hImage
                                                              title:title
                                                          highTitle:hTitle
                                                   signalCompletion:completion];
    [button.layer setCornerRadius:BGROUND];
    return button;
}

- (UILabel *)createLabelForTitle:(NSString *)title withTextColor:(UIColor *)textColor bkColor:(UIColor *)bkColor font:(UIFont *)font textAlignment:(NSTextAlignment)textAlignment rect:(CGRect)rect {
    
    UILabel *label = [NSObject createNewlineLabelWithText:title
                                                textColor:textColor
                                                  bkColor:bkColor
                                                     font:font
                                            textAlignment:textAlignment];
    
    CGFloat textWidth = CGRectGetWidth(rect);
    CGFloat textHeight = CGRectGetHeight(rect);
    CGFloat x = CGRectGetMinX(rect);
    CGFloat y = CGRectGetMinY(rect);
    
    CGSize size = [label suggestSizeForString:title width:textWidth height:textHeight];
    label.frame = CGRectMake(x, y, size.width, size.height);
    
    return label;
}

@end


@implementation HSYAlertView (Show)

- (HSYAlertView *)showAlertViewForTitle:(NSString *)title message:(NSString *)message withCancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles {
    
    [self createInterfaceForTitle:title message:message withCancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles];
    return self;
}

- (HSYAlertView *)showAlertViewForTitle:(NSString *)title message:(NSString *)message withButtonTitles:(NSArray<NSString *>*)buttonTitles {
    
    [self destroyView];
    [self showAlert];
    return self;
}

- (void)createInterfaceForTitle:(NSString *)title message:(NSString *)message withCancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... {
    
    [self destroyView];
    
    UILabel *titleLabel     = nil;
    UILabel *messageLabel   = nil;
    UIButton *cancelButton  = nil;
    UIButton *otherButton   = nil;
    
    CGFloat bg_x = 30.0f;
    CGFloat bg_h = 200.0f;
    //作为动画的承载view，backgroundView要在生成具体UI的时候设置
    self.backgroundView.frame = (CGRect){bg_x, (IPHONE_HEIGHT - bg_h)/2, IPHONE_WIDTH - bg_x*2, bg_h};
    self.backgroundImage.frame = self.backgroundView.bounds;
    
    CGFloat voidance_x = 10;
    CGFloat voidance_y = CLEARANCE;
    CGFloat maxWidth = self.backgroundView.viewWidth - voidance_x*2;
    CGFloat maxHeight = self.backgroundView.viewHeight/3;
    CGFloat bgViewHeight = 0;
    
    UIImage *image = [[HSYColorHelper shareInstance] canvasImageWithColor:[[HSYColorHelper shareInstance] navBarColor]];
    UIImage *hImage = [[HSYColorHelper shareInstance] canvasImageWithColor:[UIColor grayColor]];
    
    if ([title isLenght]) {
        
        titleLabel = [self createLabelForTitle:title
                                 withTextColor:self.titleColor
                                       bkColor:CLEAR_COLOR
                                          font:self.titleFont
                                 textAlignment:NSTextAlignmentCenter
                                          rect:CGRectMake(voidance_x, voidance_y, maxWidth, maxHeight)];
        
        [self.backgroundView addSubview:titleLabel];
        bgViewHeight = titleLabel.viewMaxY;
    }
    
    if ([message isLenght]) {
        
        CGFloat y = titleLabel ? bgViewHeight : 5;
        messageLabel = [self createLabelForTitle:message
                                   withTextColor:self.contentColor
                                         bkColor:CLEAR_COLOR
                                            font:self.contentFont
                                   textAlignment:NSTextAlignmentCenter
                                            rect:CGRectMake(voidance_x, y, maxWidth, maxHeight)];
        [self.backgroundView addSubview:messageLabel];
        bgViewHeight += messageLabel.viewMaxY;
    }
    
    
    if ([otherButtonTitles isLenght]) {
        
        @weakify(self);
        otherButton = [self createButtonForImage:image
                                   withHighImage:hImage
                                           title:otherButtonTitles
                                       highTitle:otherButtonTitles
                                signalCompletion:^(id x) {
                                    
                                    @strongify(self);
                                    self.selectButton(self, 1);
                                    [self didDismissEndingForAnimationType:self.animationType];
                                }];
        [self.backgroundView addSubview:otherButton];
        if ([cancelButtonTitle isLenght]) {
            otherButton.frame = (CGRect){voidance_y, bgViewHeight+5, (self.backgroundView.viewWidth - voidance_y*3)/2, ALERTVIEW_BUTTON_HEIGHT};
        } else {
            otherButton.frame = (CGRect){voidance_x, bgViewHeight+5, (self.backgroundView.viewWidth - voidance_x*2), ALERTVIEW_BUTTON_HEIGHT};
        }
        
        
//        va_list args;
//        va_start(args, otherButtonTitles);
//        NSString *others = va_arg(args, NSString *);
//        static NSInteger index = 2;
//        while (others) {
//            
//            @weakify(self);
//            UIButton *otherBtn = [self createButtonForImage:image
//                                              withHighImage:hImage
//                                                      title:others
//                                                  highTitle:others
//                                           signalCompletion:^(UIButton *x) {
//                                               @strongify(self);
//                                               self.selectButton(self, x.tag);
//                                           }];
//            otherBtn.tag = index;
//            [self.backgroundView addSubview:otherBtn];
//            otherBtn.frame = (CGRect){};
//            
//            index ++;
//        }
        
    }
    
    
    if ([cancelButtonTitle isLenght]) {
        
        @weakify(self);
        cancelButton = [self createButtonForImage:image
                                    withHighImage:hImage
                                            title:cancelButtonTitle
                                        highTitle:cancelButtonTitle
                                 signalCompletion:^(id x) {
                                     
                                     @strongify(self);
                                     [self didDismissEndingForAnimationType:self.animationType];
                                     self.selectButton(self, 0);
                                 }];
        [self.backgroundView addSubview:cancelButton];
        if ([otherButtonTitles isLenght]) {
            cancelButton.frame = (CGRect){otherButton.viewMaxX, bgViewHeight+5, (self.backgroundView.viewWidth - voidance_y*3)/2, ALERTVIEW_BUTTON_HEIGHT};
        } else {
            cancelButton.frame = (CGRect){voidance_x, bgViewHeight+5, (self.backgroundView.viewWidth - voidance_x*2), ALERTVIEW_BUTTON_HEIGHT};
        }
        
    }
    [self showAlert];
}

@end